import React, {Component, PropTypes} from 'react'

import TriggerGetData from './trigger'

class DropDownItem extends Component {
    render (){
        const { index, data, active, callback } = this.props;

        return (
            <li className={active?'active':null} onClick={() => callback(index)}><a href="javascript:void(0)">{data.icon?<i className={data.icon} style={{width:'1.1em'}}></i>:null}{data.name}</a></li>
        )
    }
}

export default class ReactDropDown extends Component {
    constructor() {
        super();

        this.state = {
            width: 0,
            left: 0,
            right: 0,
            top: 0,
            bottom: 'auto'
        }

        this.update = () => this.updatePosition()
    }
    shouldComponentUpdate(nextProps, nextState) {
        for(var i in this.state){
            if(this.state[i] !== nextState[i]){
                return true
            }
        }
        return false
    }
    componentDidMount() {
        this.updatePosition();
        window.addEventListener('scroll', this.update)
    }
    componentWillUnmount() {
        window.removeEventListener('scroll', this.update)
    }
    updatePosition() {
        const { target, data } = this.props;
        const pos = target.getBoundingClientRect() || {};
        const height = Math.max(document.body.clientHeight, window.innerHeight);
        const width = document.body.clientWidth;
        
        this.setState({
            width: pos.width,
            left: pos.left,
            right: (width-pos.right),
            top: pos.height+pos.top,
            bottom: ((pos.height+pos.top+data.length*32) > height ? 10: 'auto')
        })
    }
    render (){
        const { width, left, right, top, bottom } = this.state;
        const { data, selected, callback, dir } = this.props;
        
        let style = {display: 'block', left: left, top: top, bottom: bottom};

        if(dir!='left'){
            style.left = 'auto';
            style.right = right
        }

        return (
            <ul className="dropdown-menu" style={style}>
                {data.map((i, index) => <DropDownItem key={index} index={index} data={i} active={selected == index} callback={callback || function(){}} />)}
            </ul>
        )
    }
}

export class ReactDropDownFull extends TriggerGetData {
    constructor() {
        super();
        this.state = {
            isOpen: false
        }
    }
    trigger() {
        this.setState({
            isOpen: !this.state.isOpen
        })
    }
    close() {
        this.setState({
            isOpen: false
        })
    }
}